package com.gjt.channel;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.net.SocketOption;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.file.Paths;
import java.util.concurrent.Future;

/**
 * Created with Intel IDEA.
 * 异步通道
 *
 * @Auther: gjt
 * @Date: 2024/10/27 9:31
 */

public class AsynchronousChannels {
    public static void main(String[] args) {
        try {
            SocketAddress socketAddress = new InetSocketAddress(args[0], 5);

            // 异步通道
            AsynchronousSocketChannel asynchronousSocketChannel = AsynchronousSocketChannel.open();
            Future<Void> connect = asynchronousSocketChannel.connect(socketAddress);

            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            // 等待连接完成
            connect.get();

            // 从链接中读取数据
            asynchronousSocketChannel.read(byteBuffer);


            // 等待读取完成
            connect.get();

            // 回绕缓冲区 并排空
            byteBuffer.flip();
            WritableByteChannel writableByteChannel = Channels.newChannel(System.out);

            writableByteChannel.write(byteBuffer);

//            supportOptions();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    // 不同的通道支持的选项
    public static void supportOptions() throws IOException {

        printOptions(SocketChannel.open());
        printOptions(ServerSocketChannel.open());
        printOptions(AsynchronousSocketChannel.open());
        printOptions(AsynchronousServerSocketChannel.open());
        printOptions(DatagramChannel.open());
//        printOptions((NetworkChannel) FileChannel.open(Paths.get("D:\\Idea\\项目\\myboot\\socket\\src\\main\\resources\\test.xml")));

    }

    private static void printOptions(NetworkChannel channel) throws IOException {
        System.out.println(channel.getClass().getSimpleName() + "supports:");
        for(SocketOption<?> option : channel.supportedOptions()){
            // 通道支持的选项 和 默认值
            System.out.println(option.name()+ ":" + channel.getOption(option));
        }

        System.out.println();
        channel.close();
    }

}

